package microservices.spring_cloud_server.rest;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Properties;

import org.apache.ibatis.cache.CacheKey;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.plugin.Intercepts;
import org.apache.ibatis.plugin.Invocation;
import org.apache.ibatis.plugin.Plugin;
import org.apache.ibatis.plugin.Signature;
import org.apache.ibatis.session.ResultHandler;
import org.apache.ibatis.session.RowBounds;

import microservices.spring_cloud_server.vo.PageVO;
import microservices.spring_cloud_server.vo.PagedResult;

@Intercepts(@Signature(type = Executor.class, method = "query", args = { MappedStatement.class, Object.class,
		RowBounds.class, ResultHandler.class }))
public class ResultInterceptor implements Interceptor {
	@Override
	public Object intercept(Invocation invocation) throws Throwable {
		Object[] args = invocation.getArgs();
		MappedStatement ms = (MappedStatement) args[0];
		Map<?, ?> parameterObject = (Map<?, ?>) args[1];
		RowBounds rowBounds = (RowBounds) args[2];
		ResultHandler<?> resultHandler = (ResultHandler<?>) args[3];
		Executor executor = (Executor) invocation.getTarget();
		BoundSql boundSql = ms.getBoundSql(parameterObject);
		CacheKey cacheKey = executor.createCacheKey(ms, parameterObject, rowBounds, boundSql);
		List<Object> list = executor.query(ms, parameterObject, rowBounds, resultHandler, cacheKey, boundSql);
		if (parameterObject!=null&&parameterObject.containsKey("pageVO")) {
			PageVO pageVO = (PageVO) parameterObject.get("pageVO");
			PagedResult<Object> pageResult = new PagedResult<Object>();
			pageResult.setPageVO(pageVO);
			pageResult.setResultList(list);
			List<PagedResult<Object>> returnList = new ArrayList<PagedResult<Object>>();
			returnList.add(pageResult);
			return returnList;

		} else {
			return list;
		}
	}

	@Override
	public Object plugin(Object target) {
		return Plugin.wrap(target, this);
	}

	@Override
	public void setProperties(Properties properties) {
	}

}